#include "common/wifi/wifi.h"

ESP8266WebServer server(80);
ESP8266HTTPUpdateServer httpUpdater;
Ticker tickerEspNow;

typedef struct Message
{
  int keynum;
}Message;
//EspNow接收回调函数
void OnDataRecv(uint8_t * mac, uint8_t *incomingData, uint8_t len);
//
void tickerCallback();

Message dataRecs;

void OnDataRecv(uint8_t * mac, uint8_t *incomingData, uint8_t len) {
  memcpy(&dataRecs, incomingData, sizeof(dataRecs));
  Serial.print("incomingData:");
  Serial.println(dataRecs.keynum);
}

void tickerCallback()
{
  if(dataRecs.keynum != 2)
  {
    tickerMotor(dataRecs.keynum);
    dataRecs.keynum=2;
  }
}

String createWebserver()
{
    WiFi.softAP(aPSsid, aPPassword);

    IPAddress myIP = WiFi.softAPIP();
    server.on("/", handleOnConnect);
    server.onNotFound(handleNotFound);

    // 网页更新固件
    httpUpdater.setup(&server);

    server.begin();
    return myIP.toString();
}

String initEspnow()
{
    //调用esp_now_init()初始化ESP-NOW
    if (esp_now_init() != 0)
    {
        return "Error initializing ESP-NOW";
    }
    //控制者：ESP_NOW_ROLE_CONTROLLER
    //被控制者：ESP_NOW_ROLE_SLAVE
    esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
    //调用 esp_now_register_recv_cb() 注册接收回调函数。
    esp_now_register_recv_cb(OnDataRecv);
    tickerEspNow.attach_ms(50, tickerCallback);
    return WiFi.macAddress();
}

void handleOnConnect()
{
    // server.send(200, "text/plain", "Success!");
    String html = readFile("/index.html");
    html.replace("{ssid}", ssid);
    html.replace("{password}", password);
    server.send(200, "text/html", html);
}

void handleNotFound()
{
    server.send(404, "text/plain", "Not found");
}

void handleClient()
{
    if (1 == needOTA)
    {
        // 检查http服务器访问
        server.handleClient();
        return;
    }
}